Scroll Progress Bar

Polymorphism

Polymorphism is one of the fundamental principles of object-oriented programming (OOP). In C++, polymorphism allows objects of different classes to be treated as objects of a common base class. Polymorphism enables to write code that works with objects of various derived classes in a consistent manner.

Here's a sample C++ program demonstrating polymorphism with comments and Sample Output:

Program:

#include <iostream>

// Base class
class Shape {
public:
    virtual double area() const = 0; // Pure virtual function
    virtual void display() const {
        std::cout << "This is a shape." << std::endl;
    }
};

// Derived class 1: Circle
class Circle : public Shape {
public:
    Circle(double radius) : radius(radius) {}

    double area() const override {
        return 3.14159 * radius * radius;
    }

    void display() const override {
        std::cout << "This is a circle with radius " << radius << std::endl;
    }

private:
    double radius;
};

// Derived class 2: Rectangle
class Rectangle : public Shape {
public:
    Rectangle(double length, double width) : length(length), width(width) {}

    double area() const override {
        return length * width;
    }

    void display() const override {
        std::cout << "This is a rectangle with length " << length << " and width " << width << std::endl;
    }

private:
    double length;
    double width;
};

int main() {
    Shape* shapes[2]; // Array of base class pointers

    Circle circle(5.0);
    Rectangle rectangle(4.0, 6.0);

    shapes[0] = &circle;
    shapes[1] = &rectangle;

    std::cout << "Shape Information:" << std::endl;
    for (int i = 0; i < 2; i++) {
        shapes[i]->display(); // Polymorphic call to display()
        std::cout << "Area: " << shapes[i]->area() << std::endl;
        std::cout << std::endl;
    }

    return 0;
}
Output:

Shape Information:
This is a circle with radius 5
Area: 78.5398

This is a rectangle with length 4 and width 6
Area: 24
In this example:
  • A base class Shape with a pure virtual function area() and a virtual function display().
  • Two derived classes, Circle and Rectangle, inherit from Shape and provide their own implementations for area() and display().
  • In the main function, we create objects of Circle and Rectangle and store them in an array of base class pointers shapes.
  • Use a for loop to iterate through the shapes array and demonstrate polymorphism:
  • The display() function is called polymorphically, and the correct implementation is executed based on the actual object type.
  • The area() function is also called polymorphically, allowing us to compute the area of each shape without knowing their specific types.
  • This example showcases how polymorphism enables to write flexible and reusable code that works seamlessly with objects of different derived classes through a common interface (base class).

question


answer

question2


answer2